#region Imported Namespaces
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;

using PHSRAG.Insight21.SearchContext;
using DataAccess = PHSRAG.Utility.DataAccess;
using SessionCachePolicy = PHSRAG.Insight21.Policy.SessionCachePolicy;
using Calendar = PHSRAG.WebControls.Calendar;
using Policy = PHSRAG.Insight21.Policy;
using UserContext = PHSRAG.Insight21.Context.UserContext;
using PHSRAG.Insight21.Purchasing.Enumerations;
using Constants = PHSRAG.Insight21.InsightUtilities.Constants;
#endregion

namespace PHSRAG.Insight21.InsightWebControls
{
	#region Class PurchasingSearch
	/// <summary>
	/// The PurchasingSearch control is used by Purchasing summary pages.
	/// </summary>
	[ToolboxData("<{0}:PurchasingSearch runat=server />"), Designer(typeof(PurchasingSearchDesigner))]
	public class PurchasingSearch : BaseSearch, INamingContainer, ISearch
	{
		#region Constants
		private const int	DefaultDate = -60;
		private string id = "ItemId";
		private string dataStyle = "DataInput";
		private const string StartupScriptsKey = "startupScripts_DBF4645C-86C9-4c9f-B62D-219AFFC4C2EA";

		public const string FundNumberLabel = "Fund Number";
		public const string AccountNumberLabel = "Account Number";
		public const string CategoryLabel = "Category";
		public const string InvoiceNumberLabel = "Invoice Number";
		public const string JournalNumberLabel = "Journal Number";
		public const string VoucherNumberLabel = "Voucher Number";
		public const string RequestorNameLabel = "Requestor Name";
		public const string TransactionsWithinLabel = "Transactions Within";
		public const string RequisitionNumberLabel = "Requisition Number";
		public const string TransactionTypeLabel = "Transaction Type";
		public const string EnteredByLabel = "Entered By";
		public const string OrderTypeLabel = "Order Type";
		public const string TotalOrderAmountLabel = "Total Order Amount";
		public const string InvoiceDateLabel = "Invoice Date";
		public const string TransactionDateFromLabel = "Transaction Date From";
		public const string TransactionDateToLabel = "Transaction Date To";
		public const string OrderViewLabel = "Order View";
		public const string ExpenseStatusLabel = "Expense Status";
		public const string UserOrderViewLabel = "User Order View";
		public const string ReconcileTypeLabel = "Reconcile Type";
		#endregion

		#region Instance Variables
		private Policy.ICachePolicy	cachePolicy;
		private TextBox			fundNumber;
		private TextBox			accountNumber;
		private DropDownList	category;
		private TextBox			invoiceNumber;
		private TextBox			journalNumber;
		private TextBox			requestorName;
		private TextBox			requisitionNumber;
		private TextBox			voucherNumber;
		private TextBox			enteredBy;
		private TextBox			totalOrderAmount;
		private DropDownList	orderType;	
		private DropDownList	transactionType;
		private Calendar		transactionDateFrom;
		private Calendar		transactionDateTo;
		private Calendar		invoiceDate;
		private ControlCollection	controlCollection;
		private DropDownList	selectOrderView;
		private DropDownList	expenseStatusView;
		private DropDownList userOrderTypeView;
		private DropDownList transactionsWithin;
		private DropDownList reconcileType;
	
		private bool fundNumberFilterVisible = true;
		private bool journalNumberFilterVisible;
		private bool orderTypeFilterFilterVisible = true;
		private bool transactionTypeFilterVisible = true;
		private bool voucherNumberFilterVisible = true;
		private bool enteredByFilterVisible;
		private bool selectOrderViewFilterVisible;
		private	bool expenseStatusViewFilterVisible;
		private bool userOrderTypeVisible;
		private bool useDefaultDates = true;

		private bool requisitionNumberFilterVisible = true;
		private bool invoiceDateFilterVisible;
		private bool totalOrderAmountFilterVisible;
		private bool accountNumberFilterVisible = true;
		private bool categoryFilterVisible = true;
		private bool transactionsWithinFilterVisible; // for 30, 60, 90 days dropdown
		private bool reconcileTypeFilterVisible;
        private bool addUserOrderTypeSelectPrompt = true;
		
		
		// Set default to and from dates, for puchasing data is by default retreived for last 60 days
		private string DefaultFromDate		=	DateTime.Now.AddDays
			(Utility.Settings.GetKeyValue("Purchasing.DefaultFromDate", DefaultDate)).ToShortDateString();
		private string DefaultToDate		=	DateTime.Now.ToShortDateString();
		
		#endregion

		#region ISearch Members
		/// <summary>
		/// Reset the internal search state. This involves setting the value for all controls to their default values
		/// and resetting the cached state of the search context.
		/// </summary>
		public void Reset()
		{
			ResetControls(controlCollection);
			transactionDateFrom.Reset();
			transactionDateTo.Reset();		
			//transactionDateFrom.Prompt = DefaultFromDate;
			//transactionDateTo.Prompt =  DefaultToDate;	

			PurchasingSearchContext searchContext = cachePolicy.
				GetCachedObject(PurchasingSearchContext.CacheKey) as PurchasingSearchContext;
			if (searchContext != null)
				searchContext.Reset(Page.Request.Url.ToString());
		}
		/// <summary>
		/// Get the search criteria from the common search context.
		/// </summary>
		public SearchCriteria SearchCriteria
		{
			get
			{
				return ((PurchasingSearchContext)cachePolicy.
					GetCachedObject(PurchasingSearchContext.CacheKey)).GetSearchCriteria(Page.Request.Url.ToString());
			}
		}

		
		/// <summary>
		/// Get the search criteria. This is done by collecting the current values in all controls, storing them in the
		/// PurchasingSearchContext, and then returning the search criteria.
		/// </summary>
		public SearchCriteria UpdateSearchCriteria()
		{
			UserContext userContext = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);			
			return GetSearchCriteria(userContext.DomainUserId, controlCollection);
		}
		#endregion

		#region Private Properties
		/// <summary>
		/// Determine if the control is in design mode. It is if there is not HTTP context.
		/// </summary>
		private static bool IsDesignMode
		{
			get { return HttpContext.Current == null; }
		}
		#endregion

		#region Public Properties
		/// <summary>
		///  Get/Set the visibility of the Journal Number Search Filter.
		/// </summary>
		public bool JournalNumberFilterVisible
		{
			get { return journalNumberFilterVisible;  }
			set { journalNumberFilterVisible= value;}
		}
		/// <summary>
		///  Get/Set the visibility of the Fund Number Search Filter.
		/// </summary>
		public bool FundNumberFilterVisible
		{
			get { return fundNumberFilterVisible;  }
			set { fundNumberFilterVisible= value;}
		}
		/// <summary>
		///  Get/Set the visibility of the Transaction type Search Filter.
		/// </summary>
		public bool TransactionTypeFilterVisible
		{
			get { return transactionTypeFilterVisible;  }
			set { transactionTypeFilterVisible= value;}
		}
		/// <summary>
		///  Get/Set the visibility of the Order type Search Filter.
		/// </summary>
		public bool OrderTypeFilterVisible
		{
			get { return orderTypeFilterFilterVisible;  }
			set { orderTypeFilterFilterVisible= value;}
		}
		/// <summary>
		///  Get/Set the visibility of the vendor name Search Filter.
		/// </summary>
		public bool VoucherNumberFilterVisible
		{
			get { return voucherNumberFilterVisible;  }
			set { voucherNumberFilterVisible = value;}
		}
		/// <summary>
		///  Get/Set the visibility of the entered by Search Filter.
		/// </summary>
		public bool EnteredByFilterVisible
		{
			get { return enteredByFilterVisible;  }
			set { enteredByFilterVisible= value;}
		}
		
		/// <summary>
		///  Get/Set the visibility of the entered by select OrderView Search Filter.
		/// </summary>
		public bool SelectOrderViewFilterVisible
		{
			get { return selectOrderViewFilterVisible;  }
			set { selectOrderViewFilterVisible= value;}
		}

		/// <summary>
		///  Get/Set the visibility of the entered by Expense Status View Search Filter.
		/// </summary>
		public bool ExpenseStatusViewFilterVisible
		{
			get { return expenseStatusViewFilterVisible;  }
			set { expenseStatusViewFilterVisible= value;}
		}

		/// <summary>
		/// Get/Set the visibility of the user order type dropdown
		/// </summary>
		public bool UserOrderTypeVisible
		{
			get { return userOrderTypeVisible; }
			set 
			{
				userOrderTypeVisible= value;
			}
		}

		/// <summary>
		/// Get/Set the visibility of the invoice date control.
		/// </summary>
		public bool InvoiceDateFilterVisible
		{
			get { return invoiceDateFilterVisible; }
			set 
			{
				invoiceDateFilterVisible = value;
			}
		}

		/// <summary>
		/// Get/Set the visibility of the total order amount textbox.
		/// </summary>
		public bool TotalOrderAmountFilterVisible
		{
			get { return totalOrderAmountFilterVisible; }
			set 
			{
				totalOrderAmountFilterVisible = value;
			}
		}

		/// <summary>
		/// Get/Set the visibility of the requisition number textbox.
		/// </summary>
		public bool RequisitionNumberFilterVisible
		{
			get { return requisitionNumberFilterVisible; }
			set 
			{
				requisitionNumberFilterVisible = value;
			}
		}

		/// <summary>
		/// Get/Set the visibility of the account number textbox.
		/// </summary>
		public bool AccountNumberFilterVisible
		{
			get { return accountNumberFilterVisible; }
			set 
			{
				accountNumberFilterVisible = value;
			}
		}

		/// <summary>
		/// Get/Set the visibility of the category dropdown.
		/// </summary>
		public bool CategoryFilterVisible
		{
			get { return categoryFilterVisible; }
			set 
			{
				categoryFilterVisible = value;
			}
		}

		/// <summary>
		/// Get/Set the visibility of the transactions within dropdown.
		/// </summary>
		public bool TransactionsWithinFilterVisible
		{
			get { return transactionsWithinFilterVisible; }
			set 
			{
				transactionsWithinFilterVisible = value;
			}
		}

		/// <summary>
		/// Get/Set the visibility of the reconcile type dropdown
		/// </summary>
		public bool ReconcileTypeFilterVisible
		{
			get { return reconcileTypeFilterVisible; }
			set 
			{
				reconcileTypeFilterVisible = value;
			}
		}

		/// <summary>
		/// Get/Set whether or not to use default dates for the invoice date controls.
		/// </summary>
		public bool UseDefaultDates
		{
			get { return useDefaultDates; }
			set 
			{
				useDefaultDates = value;
			}
		}

		/// <summary>
		/// Get/Set whether the select prompt for user order type
		/// dropdown should be added or not.
		/// </summary>
		public bool AddUserOrderTypeSelectPrompt
		{
			get { return addUserOrderTypeSelectPrompt; }
			set 
			{
				addUserOrderTypeSelectPrompt = value;
			}
		}
		#endregion

		#region Overrides
		/// <summary>
		/// Create all controls. Notice that the creation is more than just instantiating the controls. It also involves
		/// in generating the underlying HTML so that the controls shows up per the need.
		/// </summary>
		protected override void CreateChildControls()
		{
			CreateControls();
			GenerateControlTree();
		}
		/// <summary>
		/// Initializes the cachepolicy. Create and cache a PurchasingSearchContext object if necessary.
		/// Note that controls whose state must persist in the view state MUST be created BEFORE OnInit completes. We do
		/// this simply by invoking EnsureChildControls().
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnInit(EventArgs e)
		{
			cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];
			PurchasingSearchContext searchContext = cachePolicy.GetCachedObject(PurchasingSearchContext.CacheKey) as PurchasingSearchContext;
			if (searchContext == null)
			{
				searchContext = new PurchasingSearchContext(cachePolicy);
				searchContext.Load(DataAccess.ConnectionString);
				searchContext.Cache();
			}
			EnsureChildControls();
			base.OnInit(e);
			searchContext.GetSearchCriteria(Page.Request.Url.ToString(), controlCollection);
			
		}

		
		/// <summary>
		/// Initialize the contents of all controls on first load. If the PurchasingSearchContext is not cached yet, a
		/// new instance is created and cached.
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnLoad(EventArgs e)
		{
			PurchasingSearchContext searchContext = (PurchasingSearchContext)cachePolicy.GetCachedObject(PurchasingSearchContext.CacheKey);	
			if (!Page.IsPostBack)
			{
				if(transactionTypeFilterVisible)
					LoadDropDownList(transactionType, searchContext.TransactionTypeValues, id, 1, true);

				if (categoryFilterVisible)
					LoadDropDownList(category, searchContext.Category, id, 0, true);
								
				// if the control needs to show Journal data, 
				// Journal Number filter would be enabled on the page,
				// and Ordertype will have to include the JE value in the dropdown,
				// check if we need JournalNumberFilterVisible, load the dropdown with all transaction type list..
				if(JournalNumberFilterVisible && orderTypeFilterFilterVisible)
				{
					LoadDropDownList(orderType, searchContext.ALLTransactionTypes, id, -1, true);
				}
										
				else if(orderTypeFilterFilterVisible)
				{
					LoadDropDownList(orderType, searchContext.POAPOrderTypes, id, -1, true);
				}
				if( selectOrderViewFilterVisible && expenseStatusViewFilterVisible)
				{
					LoadDropDownList(selectOrderView, searchContext.SelectOrderViewValues, id, 1, true);
					LoadDropDownList(expenseStatusView, searchContext.ExpenseStatusValues, id, 3, true);
				}

				if (userOrderTypeVisible) 
				{
					LoadDropDownList(userOrderTypeView, searchContext.UserOrderTypeValues, id, 0, addUserOrderTypeSelectPrompt);
				}
				
				SetControlState(searchContext.GetSearchCriteria(Page.Request.Url.ToString(), controlCollection));
			}
			else
			{
				SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                if(JournalNumberFilterVisible && OrderTypeFilterVisible && !String.IsNullOrEmpty(journalNumber.Text))
                {
					orderType.SelectedIndex = orderType.Items.IndexOf(orderType.Items.FindByText("JE"));
					searchCriteria[InsightUtilities.Constants.PurchasingSearchKey.OrderTypeKey] = orderType.SelectedIndex.ToString();
					transactionDateFrom.Reset();
					transactionDateFrom.Prompt = "";
					searchCriteria.Remove(InsightUtilities.Constants.PurchasingSearchKey.TransactionDateFromKey);
					transactionDateTo.Reset();
					transactionDateTo.Prompt = "";
					searchCriteria.Remove(InsightUtilities.Constants.PurchasingSearchKey.TransactionDateToKey);
					expenseStatusView.SelectedIndex = expenseStatusView.Items.IndexOf(expenseStatusView.Items.FindByText("Paid"));
					searchCriteria[InsightUtilities.Constants.PurchasingSearchKey.ExpenseStatusViewKey] = expenseStatusView.SelectedIndex.ToString();
				}
				else if(OrderTypeFilterVisible && orderType.SelectedItem.Text == "JE")
				{
					expenseStatusView.SelectedIndex = expenseStatusView.Items.IndexOf(expenseStatusView.Items.FindByText("Paid"));
					searchCriteria[InsightUtilities.Constants.PurchasingSearchKey.ExpenseStatusViewKey] = expenseStatusView.SelectedIndex.ToString();
				}
                if (transactionsWithin != null)
                {
                    if (transactionsWithin.SelectedValue != "-- Select --")
                    {

                        transactionDateFrom.Reset();
                        transactionDateFrom.Prompt = "";
                        transactionDateTo.Reset();
                        transactionDateTo.Prompt = "";
                    }

                }
			}
		}

        /// <summary>
        /// Set the state for all constituent controls, and register a client script block for the express purpose of
        /// validating the date ranges of all paired Calendar controls in this search block.
        /// </summary>
        /// <param name="e">Argument associated with the event</param>
        /// <remarks>
        /// <protocolId>Why are the actions taken in this method not being done on control load?</protocolId>
        /// <protocolId>During the non-postback construction of the control, the OnLoad method is invoked BEFORE the
        /// CreateChildControls method. The actual creation of constitutent controls are done within the context of
        /// the CreateChildControls methos. Setting the state of control relies on (obviously) the fact that the controls
        /// have been created. So, setting the state in OnLoad for the non-postback condition would fail.</protocolId>
        /// <protocolId>Interestingly, the sequence of method invocations reverses on postback: CreateChildControls is invoked
        /// before OnLoad.</protocolId>
        /// </remarks>
        protected override void OnPreRender(EventArgs e)
        {
			base.OnPreRender (e);

			  if (!IsDesignMode)
			  {
				  if (!Page.ClientScript.IsClientScriptBlockRegistered(Constants.ValidateDateRangeScriptKey))
				  {
					  string script = string.Format(
						  "<script language=\"javascript\">\r\n" +
						  "function ValidateDateRange()\r\n" +
						  "{{\r\n" +
						  "\t var transactionFromText = null \r\n" +
						  "\t var transactionToText = null \r\n" +
						  "\tif (document.getElementById(\"{0}\") != null)\r\n" +
						  "\t\t transactionFromText = document.getElementById(\"{0}\").value;\r\n" +
						  "\tif (document.getElementById(\"{1}\") != null)\r\n" +
						  "\t\t transactionToText = document.getElementById(\"{1}\").value;\r\n" +
						  "\tif (transactionFromText != null && transactionFromText != \"\" && transactionToText != null && transactionToText != \"\")\r\n" +
						  "\t{{\r\n" +
						  "\t\tvar transactionFromDate = new Date(transactionFromText);\r\n" +
						  "\t\tvar transactionToDate = new Date(transactionToText);\r\n" +
						  "\t\tif (transactionFromDate > transactionToDate)\r\n" +
						  "\t\t{{\r\n" +
						  "\t\t\talert('Transaction From Date cannot be after Transaction To Date.');\r\n" +
						  "\t\t\tdocument.getElementById(\"{1}\").focus();\r\n" +
                          "\t\t\treturn false;\r\n" +
                          "\t\t}}\r\n" +
                          "\t\treturn true;\r\n" +
                          "\t}}\r\n" +
                          "\treturn true;\r\n" +
                          "}}\r\n" +
						  "</script>\r\n",
						  (transactionDateFrom == null) ? "" : transactionDateFrom.SelectedDateClientId,
						  (transactionDateTo == null) ? "" : transactionDateTo.SelectedDateClientId);

					  Page.ClientScript.RegisterClientScriptBlock(GetType( ), Constants.ValidateDateRangeScriptKey, script);
				  }	
				
				  const string PScriptKey = "PurchasingManagedScript";
				  if (!Page.ClientScript.IsClientScriptBlockRegistered(PScriptKey))
				  {
					  if (orderType != null)
					  {
						  string script = string.Format(
							  "<script language=\"javascript\">\r\n" +
							  "function ManagePONumber(fieldId)\r\n" +
							  "{{\r\n" +						
							  "\tif (document.getElementById(fieldId).value.length != 0)\r\n" +
							  "\t{{\r\n" +
							  "\t\t document.getElementById('" + orderType.ClientID + "').selectedIndex = 2;\r\n" +
							  "\t\t document.getElementById('" + voucherNumber.ClientID + "').value = '';\r\n" +
							  "\t}}\r\n" +										
							  "}}\r\n" +
							  "function ManageVoucherNumber(fieldId)\r\n" +
							  "{{\r\n" +						
							  "\tif (document.getElementById('" + voucherNumber.ClientID + "').value.length != 0)\r\n" +
							  "\t{{\r\n" +
							  "\t\t document.getElementById('" + orderType.ClientID + "').selectedIndex = 3;\r\n" +
							  "\t\t document.getElementById(fieldId).value = '';\r\n" +
							  "\t}}\r\n" +										
							  "}}\r\n" +
							  "function ManageOrderType(fieldId)\r\n" +
							  "{{\r\n" +
							  "\tvar orderTypeSelected = document.getElementById('" + orderType.ClientID + "').selectedIndex; \r\r" +
							  "\tif ( orderTypeSelected == 3 || orderTypeSelected == 4)\r\n" +
							  "\t{{\r\n" +						
							  "\t\t document.getElementById(fieldId).value='';\r\n" +
							  "\t\t document.getElementById(fieldId).disabled=true;\r\n" +
							  "\t}}\r\n" +
							  "\telse \r\n" +
							  "\t{{\r\n" +
							  "\t\t document.getElementById(fieldId).disabled=false;\r\n" +
							  "\t}}\r\n" +
							  "\tif ( orderTypeSelected == 2 || orderTypeSelected == 4)\r\n" +
							  "\t{{\r\n" +						
							  "\t\t document.getElementById('" + voucherNumber.ClientID + "').value='';\r\n" +
							  "\t\t document.getElementById('" + voucherNumber.ClientID + "').disabled=true;\r\n" +
							  "\t}}\r\n" +
							  "\telse \r\n" +
							  "\t{{\r\n" +
							  "\t\t document.getElementById('" + voucherNumber.ClientID + "').disabled=false;\r\n" +
							  "\t}}\r\n" +
							  "}}\r\n" +
							  "</script>\r\n");

						  Page.ClientScript.RegisterClientScriptBlock(GetType( ), PScriptKey, script);
					  }
				  }
			  }       
        }

		/// <summary>
		/// Render the control. Note that we simply ensure that all child controls are created, and then delegate the
		/// call back to the base class.
		/// </summary>
		/// <param name="writer">The writer to use for rendering</param>
		protected override void Render(HtmlTextWriter writer)
		{
			EnsureChildControls();
			base.Render(writer);
		}
		#endregion

		#region Private Methods
		/// <summary>
		/// Create all controls in the CommonSearch.
		/// </summary>
		private void CreateControls()
		{			
			Controls.Clear();
			controlCollection = new ControlCollection(this);

            if(FundNumberFilterVisible || IsDesignMode)
			{
				fundNumber = new TextBox();
				fundNumber.ID = InsightUtilities.Constants.FundIDKey;
				fundNumber.CssClass = dataStyle;
				fundNumber.Attributes["Label"] = FundNumberLabel;				
                controlCollection.Add(fundNumber);
			}

			if (accountNumberFilterVisible || IsDesignMode) 
			{
				accountNumber = new TextBox();
				accountNumber.ID = InsightUtilities.Constants.PurchasingSearchKey.AccountNumberKey;
				accountNumber.CssClass = dataStyle;
				accountNumber.Attributes["Label"] = AccountNumberLabel;
                controlCollection.Add(accountNumber);
			}

			if (categoryFilterVisible || IsDesignMode) 
			{
				category = new DropDownList();
				category.ID = InsightUtilities.Constants.PurchasingSearchKey.CategoryIdKey;
				category.CssClass = dataStyle;
				category.Attributes["Label"]= CategoryLabel;
                controlCollection.Add(category);
			}

			invoiceNumber = new TextBox();
			invoiceNumber.ID = InsightUtilities.Constants.PurchasingSearchKey.InvoiceNumberKey;
			invoiceNumber.CssClass = dataStyle;
			invoiceNumber.Attributes["Label"] = InvoiceNumberLabel;
            controlCollection.Add(invoiceNumber);

						
			if(JournalNumberFilterVisible || IsDesignMode)
			{
				journalNumber = new TextBox();
				journalNumber.ID = InsightUtilities.Constants.PurchasingSearchKey.JournalNumberKey;
				journalNumber.CssClass = dataStyle;
				journalNumber.Attributes["Label"] = JournalNumberLabel;
                controlCollection.Add(journalNumber);
			}
			if(VoucherNumberFilterVisible || IsDesignMode)
			{
				voucherNumber			= new TextBox();
				voucherNumber.ID		= InsightUtilities.Constants.PurchasingSearchKey.VoucherNumberKey;
				voucherNumber.CssClass	= dataStyle;
				voucherNumber.Attributes["Label"] = VoucherNumberLabel;
				voucherNumber.Attributes["onchange"] = "OnVoucherNumberChanged();";
                controlCollection.Add(voucherNumber);
			}
            
			requestorName = new TextBox();
			requestorName.ID = InsightUtilities.Constants.PurchasingSearchKey.RequestorNameKey;
			requestorName.CssClass = dataStyle;
			requestorName.Attributes["Label"] = RequestorNameLabel;
            controlCollection.Add(requestorName);

			if (transactionsWithinFilterVisible || IsDesignMode) 
			{
				transactionsWithin = new DropDownList();
				transactionsWithin.ID = InsightUtilities.Constants.PurchasingSearchKey.DaysTransactionsWithinKey;
				transactionsWithin.CssClass = dataStyle;
				transactionsWithin.Items.Add(CommonSearch.SelectPrompt);
				transactionsWithin.Items.Add(new ListItem("30 Days", ((int)DateWithin.ThirtyDays).ToString()));
				transactionsWithin.Items.Add(new ListItem("60 Days", ((int)DateWithin.SixtyDays).ToString()));
				transactionsWithin.Items.Add(new ListItem("90 Days", ((int)DateWithin.NinetyDays).ToString()));
				transactionsWithin.SelectedIndex = 0;
				transactionsWithin.Attributes["Label"] = TransactionsWithinLabel;
                controlCollection.Add(transactionsWithin);
			}

			if (requisitionNumberFilterVisible || IsDesignMode) 
			{
				requisitionNumber = new TextBox();
				requisitionNumber.ID = InsightUtilities.Constants.PurchasingSearchKey.RequisitionNumberKey;
				requisitionNumber.CssClass = dataStyle;
				requisitionNumber.Attributes["Label"] = RequisitionNumberLabel;
                controlCollection.Add(requisitionNumber);
			}
			
			if(transactionTypeFilterVisible || IsDesignMode)
			{
				transactionType = new DropDownList();
				transactionType.ID = InsightUtilities.Constants.PurchasingSearchKey.TransactionTypeKey;
				transactionType.CssClass = dataStyle;
				transactionType.Attributes["Label"] = TransactionTypeLabel;
                controlCollection.Add(transactionType);
			}

			if(enteredByFilterVisible || IsDesignMode)
			{
				enteredBy = new TextBox();
				enteredBy.ID = InsightUtilities.Constants.PurchasingSearchKey.EnteredByKey;
				enteredBy.CssClass = dataStyle;
				enteredBy.Attributes["Label"]= EnteredByLabel;
                controlCollection.Add(enteredBy);
			}
			if(orderTypeFilterFilterVisible || IsDesignMode)
			{
				orderType = new DropDownList();
				orderType.ID = InsightUtilities.Constants.PurchasingSearchKey.OrderTypeKey;
				orderType.CssClass = dataStyle;
				orderType.Attributes["Label"] = OrderTypeLabel;
				orderType.Attributes["onchange"] = "OnOrderTypeChanged();";
                controlCollection.Add(orderType);
			}

			if (totalOrderAmountFilterVisible || IsDesignMode) 
			{
				totalOrderAmount = new TextBox();
				totalOrderAmount.ID = InsightUtilities.Constants.PurchasingSearchKey.TotalOrderAmountKey;
				totalOrderAmount.CssClass = dataStyle;
				totalOrderAmount.Attributes["Label"] = TotalOrderAmountLabel;
                totalOrderAmount.Attributes["onblur"] = "ValidateAmountInput(this);return false;";

				if (!Page.ClientScript.IsStartupScriptRegistered(StartupScriptsKey)) 
				{
					Page.ClientScript.RegisterStartupScript(GetType( ), StartupScriptsKey,"<script language=\"javascript\">\r\n"+
						"function ValidateAmountInput(field)\r\n"+
						"{\r\n"+
						"var amountExpression = new RegExp(\"^[0-9]*(\\\\.)?[0-9]{0,2}$\" ,\"g\");\r\n"+
						"if (field.value != '' && !field.value.match(amountExpression))\r\n"+
						"{\r\n"+
						"alert('Amount has to be a numeric value and no more than 2 digits are allowed to proceed a decimal point ');\r\n field.focus();\r\n"+
						"}\r\n"+
						"}\r\n</script>");
				}

				controlCollection.Add(totalOrderAmount);
			}

			if (invoiceDateFilterVisible || IsDesignMode)
			{
				invoiceDate = new Calendar();
				invoiceDate.ID = InsightUtilities.Constants.PurchasingSearchKey.InvoiceDateKey;
				invoiceDate.Attributes["Label"] = InvoiceDateLabel;
                controlCollection.Add(invoiceDate);
			}
					
			transactionDateFrom = new Calendar();		
			transactionDateFrom.ID = InsightUtilities.Constants.PurchasingSearchKey.TransactionDateFromKey;
			transactionDateFrom.Attributes["Label"] = TransactionDateFromLabel;
            controlCollection.Add(transactionDateFrom);
		
			
			transactionDateTo = new Calendar();			
			transactionDateTo.ID = InsightUtilities.Constants.PurchasingSearchKey.TransactionDateToKey;
			transactionDateTo.Attributes["Label"] = TransactionDateToLabel;			
            controlCollection.Add(transactionDateTo);
			

			if(SearchCriteria["TransactionDateFrom"] != null && SearchCriteria["TransactionDateTo"] != null)
			{
			
				transactionDateFrom.Prompt = SearchCriteria["TransactionDateFrom"];
				transactionDateTo.Prompt = SearchCriteria["TransactionDateTo"];
			}
			else if (!Page.IsPostBack && useDefaultDates)
			{
				transactionDateFrom.Prompt = DefaultFromDate;
				transactionDateTo.Prompt = DefaultToDate;
			}

			if(selectOrderViewFilterVisible || IsDesignMode)
			{
				selectOrderView = new DropDownList();
				selectOrderView.ID = InsightUtilities.Constants.PurchasingSearchKey.SelectOrderViewKey;
				selectOrderView.CssClass = dataStyle;
				selectOrderView.Attributes["Label"] = OrderViewLabel;
                controlCollection.Add(selectOrderView);
			}

			//			selectOrderView.Items.Add(new ListItem("Order Summary", "1"));
			//			selectOrderView.Items.Add(new ListItem("Order Details", "2"));
			
			//			selectOrderView.SelectedIndex = 0;
			//			selectOrderView.Attributes["Label"] = "Select View";

			if(expenseStatusViewFilterVisible || IsDesignMode)
			{
				expenseStatusView = new DropDownList();
				expenseStatusView.ID = InsightUtilities.Constants.PurchasingSearchKey.ExpenseStatusViewKey;
				expenseStatusView.CssClass = dataStyle;
				expenseStatusView.Attributes["Label"] = ExpenseStatusLabel;
                controlCollection.Add(expenseStatusView);
			}

			//			expenseStatusView.Items.Add(new ListItem("All", "1"));
			//			expenseStatusView.Items.Add(new ListItem("Paid", "2"));
			//			expenseStatusView.Items.Add(new ListItem("UnPaid", "3"));
			//			expenseStatusView.SelectedIndex = 2;
			//			expenseStatusView.Attributes["Label"] = "Expense Status";

			if(userOrderTypeVisible || IsDesignMode)
			{
				userOrderTypeView = new DropDownList();
				userOrderTypeView.ID = InsightUtilities.Constants.PurchasingSearchKey.UserOrderTypeViewKey;
				userOrderTypeView.CssClass = dataStyle;
				userOrderTypeView.Attributes["Label"] = UserOrderViewLabel;
                controlCollection.Add(userOrderTypeView);
			}

			if (reconcileTypeFilterVisible || IsDesignMode) 
			{
				reconcileType = new DropDownList();
				reconcileType.ID = InsightUtilities.Constants.PurchasingSearchKey.ReconcileTypeKey;
				reconcileType.CssClass = dataStyle;
				reconcileType.Items.Add(new ListItem("Unmatched Orders", "0"));
				reconcileType.Items.Add(new ListItem("Matched Orders", "1"));
				reconcileType.Attributes["Label"] = ReconcileTypeLabel;
                controlCollection.Add(reconcileType);
			}
		}


		/// <summary>
		/// The table contains the following: 
		/// Row 1 Col 1: Account # Label 
		/// Row 1 Col 2: Account TextBox
		/// Row 2 Col 1: Invoice # Label
		/// Row 2 Col 2: Invoice TextBox
		/// Row 3 Col 1: Requestor Label
		/// Row 3 Col 2: Requestor TextBox
		/// Row 4 Col 1: Transaction Type Label
		/// Row 4 Col 2: Transaction Type Dropdown
		/// Row 5 Col 1: Entered By Label
		/// Row 5 Col 2: Entered By TextBox 
		/// Row 6 Col 1: Order view Label
		/// Row 6 Col 2: Order View DropDown 
		/// </summary>
		private Table GenerateControlTreeForFirstSection()
		{
			Table t = new Table();
			t.CssClass = "Search";
            TableRow r1 = new TableRow();
			t.Rows.Add(r1);

			if (accountNumberFilterVisible) 
			{
				TableCell r1c1 = new TableCell();
				r1c1.Attributes["align"] = "right";
				r1c1.Text = "<nobr>Account&nbsp;#:</nobr>"; 
				r1.Cells.Add(r1c1);

				TableCell r1c2 = new TableCell();
				r1.Cells.Add(r1c2);
				r1c2.Controls.Add(accountNumber);
			}

			TableRow r2 = new TableRow();
			t.Rows.Add(r2);
			TableCell r2c1 = new TableCell();
			r2c1.Attributes["align"] = "right";
			r2c1.Text = "<nobr>Invoice&nbsp;#:</nobr>";
			r2.Cells.Add(r2c1);

			TableCell r2c2 = new TableCell();
			r2.Cells.Add(r2c2);
			r2c2.Controls.Add(invoiceNumber);

			TableRow r3 = new TableRow();
			t.Rows.Add(r3);
			TableCell r3c1 = new TableCell();
			r3c1.Attributes["align"] = "right";
			r3c1.Text =  "<nobr>Requestor:</nobr>";
			r3.Cells.Add(r3c1);

			TableCell r3c2 = new TableCell();
			r3.Cells.Add(r3c2);
			r3c2.Controls.Add(requestorName);

			if(transactionTypeFilterVisible)
			{
				TableRow r4 = new TableRow();
				t.Rows.Add(r4);
				TableCell r4c1 = new TableCell();
				r4c1.Attributes["align"] = "right";
				r4c1.Text =  "<nobr>Transaction&nbsp;Type:</nobr>";
				r4.Cells.Add(r4c1);
	
				TableCell r4c2 = new TableCell();
				r4.Cells.Add(r4c2);
				r4c2.Controls.Add(transactionType);
			}

			if(enteredByFilterVisible)
			{
				TableRow r5 = new TableRow();
				t.Rows.Add(r5);
				TableCell r5c1 = new TableCell();
				r5c1.Attributes["align"] = "right";
				r5c1.Text =  "<nobr>Entered&nbsp;By:</nobr>";
				r5.Cells.Add(r5c1);
	
				TableCell r5c2 = new TableCell();
				r5.Cells.Add(r5c2);
				r5c2.Controls.Add(enteredBy);

			}

			if(selectOrderViewFilterVisible)
			{
				TableRow r6 = new TableRow();
				t.Rows.Add(r6);
				TableCell r6c1 = new TableCell();
				r6c1.Attributes["align"] = "right";
				r6c1.Text =  "<nobr>Order&nbsp;View:</nobr>";
				r6.Cells.Add(r6c1);

				TableCell r6c2 = new TableCell();
				r6.Cells.Add(r6c2);
				r6c2.Controls.Add(selectOrderView);
			}	
	
			if (transactionsWithinFilterVisible) 
			{
				TableRow r7 = new TableRow();
				t.Rows.Add(r7);
				TableCell r7c1 = new TableCell();
				r7c1.Attributes["align"] = "right";
				r7c1.Text = "<nobr>Transactions&nbsp;Within:</nobr>";
				r7.Cells.Add(r7c1);

				TableCell r7c2 = new TableCell();
				r7.Cells.Add(r7c2);
				r7c2.Controls.Add(transactionsWithin);
			}

			return t;
		}
		/// <summary>
		/// The table contains the following: 
		/// Row 1 Col 1: Category Label 
		/// Row 1 Col 2: Category TextBox
		/// Row 2 Col 1: Voucher # Label
		/// Row 2 Col 2: Voucher TextBox
		/// Row 3 Col 1: Requisition # Label
		/// Row 3 Col 2: Requisition # TextBox
		/// Row 4 Col 1: Transaction Date From Label	
		/// Row 4 Col 2: Transaction Date From Calendar 
		/// Row 4 Col 3: Transaction Date To Label	
		/// Row 4 Col 4: Transaction Date To Calendar 
		/// Row 5 Col 1: Expense Status View Label
		/// Row 5 Col 2: Expense Status View DropDown
		/// </summary>
		private Table GenerateControlTreeForSecondSection()
		{
			Table t = new Table();
			t.CssClass = "Search";
			TableRow r1 = new TableRow();
			t.Rows.Add(r1);

			if (categoryFilterVisible) 
			{
				TableCell r1c1 = new TableCell();
				r1c1.Attributes["align"] = "right";
				r1c1.Text = "<nobr>Category:</nobr>"; 
				r1.Cells.Add(r1c1);

				TableCell r1c2 = new TableCell();
				r1.Cells.Add(r1c2);
				r1c2.Controls.Add(category);
			}

			if(VoucherNumberFilterVisible)
			{
				TableRow r2 = new TableRow();
				t.Rows.Add(r2);
				TableCell r2c1 = new TableCell();
				r2c1.Attributes["align"] = "right";
				r2c1.Text = "<nobr>Voucher&nbsp;#:</nobr>";
				r2.Cells.Add(r2c1);

				TableCell r2c2 = new TableCell();
				r2.Cells.Add(r2c2);
				r2c2.Controls.Add(voucherNumber);
			}

			if (requisitionNumberFilterVisible) 
			{
				TableRow r3 = new TableRow();
				t.Rows.Add(r3);
				TableCell r3c1 = new TableCell();
				r3c1.Attributes["align"] = "right";
				r3c1.Text =  "<nobr>Requisition&nbsp;#:</nobr>";
				r3.Cells.Add(r3c1);

				TableCell r3c2 = new TableCell();
				r3.Cells.Add(r3c2);
				r3c2.Controls.Add(requisitionNumber);
			}

			if (invoiceDateFilterVisible) 
			{
				TableRow r4 = new TableRow();
				t.Rows.Add(r4);
				TableCell r4c1 = new TableCell();
				r4.Cells.Add(r4c1);
				r4c1.Attributes["align"] = "right";
				r4c1.Text =  "<nobr>Invoice&nbsp;Date:</nobr>";
		
				TableCell r4c2 = new TableCell();
				r4.Cells.Add(r4c2);
                r4c2.Controls.Add(IsDesignMode ? (Control)new LiteralControl(Calendar.DesignTimeHTML) : (Control)invoiceDate);
			}

			if (totalOrderAmountFilterVisible) 
			{
				TableRow r5 = new TableRow();
				t.Rows.Add(r5);
				TableCell r5c1 = new TableCell();
				r5c1.Attributes["align"] = "right";
				r5c1.Text = "<nobr>Total Order Amount:</nobr>";
				r5.Cells.Add(r5c1);

				TableCell r5c2 = new TableCell();
				r5.Cells.Add(r5c2);
				r5c2.Controls.Add(totalOrderAmount);
			}
		
			TableRow r6 = new TableRow();
			t.Rows.Add(r6);
			TableCell r6c1 = new TableCell();
			r6.Cells.Add(r6c1);
			r6c1.Attributes["align"] = "right";
			r6c1.Text =  "<nobr>Transaction&nbsp;Date&nbsp;From:</nobr>";
		
			TableCell r6c2 = new TableCell();
			r6.Cells.Add(r6c2);
            r6c2.Controls.Add(IsDesignMode ? (Control)new LiteralControl(Calendar.DesignTimeHTML) : (Control)transactionDateFrom);
				
			TableCell r6c3 = new TableCell();
			r6c3.Attributes["align"] = "left";
			r6c3.Text = "<nobr>To:</nobr>";
			r6.Cells.Add(r6c3);

			TableCell r6c4 = new TableCell();
			r6.Cells.Add(r6c4);
			r6c4.Controls.Add(IsDesignMode
                ? (Control)new LiteralControl(Calendar.DesignTimeHTML)
				:(Control)transactionDateTo);

			if(expenseStatusViewFilterVisible)
			{
				TableRow r7 = new TableRow();
				t.Rows.Add(r7);
				TableCell r7c1 = new TableCell();
				r7c1.Attributes["align"] = "right";
				r7c1.Text =  "<nobr>Expense&nbsp;Status:</nobr>";
				r7.Cells.Add(r7c1);

				TableCell r7c2 = new TableCell();
				r7.Cells.Add(r7c2);
				r7c2.Controls.Add(expenseStatusView);
			}		
			return t;
		}

		/// <summary>
		/// The table contains the following: 
		/// Row 1 Col 1: Fund # Label 
		/// Row 1 Col 2: Fund # TextBox
		/// Row 2 Col 1: Journal # Label
		/// Row 2 Col 2: Journal # TextBox
		/// Row 3 Col 1: Order Type Label
		/// Row 3 Col 2: Order Type DropDown

		/// </summary>		
		private Table GenerateControlTreeForThirdSection()
		{

			Table t = new Table();
			t.CssClass = "Search";
			TableRow r1 = new TableRow();
			t.Rows.Add(r1);

			if(FundNumberFilterVisible)
			{
				
				TableCell r1c1 = new TableCell();
				r1c1.Attributes["align"] = "right";
				r1c1.Text = "<nobr>Fund&nbsp;#:</nobr>";
				r1.Cells.Add(r1c1);

				TableCell r1c2 = new TableCell();
				r1.Cells.Add(r1c2);
				r1c2.Controls.Add(fundNumber);
			}

			
			if(JournalNumberFilterVisible)
			{
				TableRow r2 = new TableRow();
				t.Rows.Add(r2);
				TableCell r2c1 = new TableCell();
				r2c1.Attributes["align"] = "right";
				r2c1.Text = "<nobr>Journal&nbsp;#:</nobr>";
				r2.Cells.Add(r2c1);

				TableCell r2c2 = new TableCell();
				r2.Cells.Add(r2c2);
				r2c2.Controls.Add(journalNumber);

			}

			if(orderTypeFilterFilterVisible)
			{
				TableRow r3 = new TableRow();
				t.Rows.Add(r3);
				TableCell r3c1 = new TableCell();
				r3c1.Attributes["align"] = "right";
				r3c1.Text = "<nobr>Order&nbsp;Type:</nobr>";
				r3.Cells.Add(r3c1);

				TableCell r3c2 = new TableCell();
				r3.Cells.Add(r3c2);
				r3c2.Controls.Add(orderType);

			}
			if(userOrderTypeVisible)
			{
				TableRow r4 = new TableRow();
				t.Rows.Add(r4);
				TableCell r4c1 = new TableCell();
				r4.Cells.Add(r4c1);
				r4c1.Attributes["align"] = "right";
				r4c1.Text = "User Order Type:";

				TableCell r4c2 = new TableCell();
				r4.Cells.Add(r4c2);
				r4c2.Controls.Add(userOrderTypeView);
			}

			if(reconcileTypeFilterVisible)
			{
				TableRow r5 = new TableRow();
				t.Rows.Add(r5);
				TableCell r5c1 = new TableCell();
				r5.Cells.Add(r5c1);
				r5c1.Attributes["align"] = "right";
				r5c1.Text = "Reconcile Type:";

				TableCell r5c2 = new TableCell();
				r5.Cells.Add(r5c2);
				r5c2.Controls.Add(reconcileType);
			}

			return t;
		}
		/// <summary>
		/// Setup the control tree to reflect the actual (and exact) layout of the controls within the CommonSearch.
		/// </summary>
		private void GenerateControlTree()
		{
            string searchClientId = ((Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey]).GetCachedObject(Constants.SearchButtonClientIDKey) as string;
            if (searchClientId == null)
                searchClientId = "expandingPanel_commonSearch_search";

			Table t1 = new Table();
			t1.CssClass = "Search";
            t1.Attributes.Add("onkeypress", "return ClickButton(event, '" + searchClientId + "')");
            Controls.Add(t1);

			TableRow t1r1 = new TableRow();
			t1.Rows.Add(t1r1);

			TableCell t1r1c1 = new TableCell();
			t1r1c1.Attributes["valign"] = "top";
			t1r1.Cells.Add(t1r1c1);
			t1r1c1.Controls.Add(GenerateControlTreeForFirstSection());

			TableCell separator = new TableCell();
			separator.CssClass = "Separator";
			separator.Controls.Add(new LiteralControl("&nbsp;"));
			t1r1.Cells.Add(separator);
			
			TableCell t1r1c2 = new TableCell();
			t1r1c2.Attributes["valign"] = "top";
			t1r1.Cells.Add(t1r1c2);
			t1r1c2.Controls.Add(GenerateControlTreeForSecondSection());

			separator = new TableCell();
			separator.CssClass = "Separator";
			separator.Controls.Add(new LiteralControl("&nbsp;"));
			t1r1.Cells.Add(separator);
			TableCell t1r1c3 = new TableCell();
			t1r1c3.Attributes["valign"] = "top";
			t1r1.Cells.Add(t1r1c3);
			t1r1c3.Controls.Add(GenerateControlTreeForThirdSection());
		}

		/// <summary>
		/// Helper method to load a drop-down-list with data.
		/// </summary>
		/// <param name="list">Reference to the drop-down-list to load</param>
		/// <param name="table">DataTable which contains data to load</param>
		/// <param name="valueColumnName">Name of the column which holds the value for the row</param>
		/// <param name="selectedIndex">Sets the Selected Index on the drop down, typically is set to defaults values for Order type, and Transaction Type dropdowns.</param>
		private static void LoadDropDownList(DropDownList list, DataTable table, string valueColumnName, int selectedIndex, bool addSelectPrompt)
		{
			if (addSelectPrompt)
				list.Items.Add(new ListItem(CommonSearch.SelectPrompt,"-1"));
			foreach (DataRow row in table.Rows)
			{
				list.Items.Add(new ListItem((string)row[0], row[valueColumnName].ToString()));
			}
			list.SelectedIndex = selectedIndex;

			list.Enabled = (list.Items.Count > 1);
		}

		/// <summary>
		/// Set the state of all child controls to reflect the search criteria (if any).
		/// </summary>
		/// <param name="searchCriteria">The search criteia (name/value pairs)</param>
		protected override void SetControlState(SearchCriteria searchCriteria)
		{
            base.SetControlState(searchCriteria);

            if (searchCriteria != null)
			{
				if(JournalNumberFilterVisible && OrderTypeFilterVisible && !String.IsNullOrEmpty(journalNumber.Text))
				{
					orderType.SelectedIndex = orderType.Items.IndexOf(orderType.Items.FindByText("JE"));
					searchCriteria[InsightUtilities.Constants.PurchasingSearchKey.OrderTypeKey] = orderType.SelectedIndex.ToString();
					transactionDateFrom.Reset();
					transactionDateFrom.Prompt = "";
					searchCriteria.Remove(InsightUtilities.Constants.PurchasingSearchKey.TransactionDateFromKey);
					transactionDateTo.Reset();
					transactionDateTo.Prompt = "";
					searchCriteria.Remove(InsightUtilities.Constants.PurchasingSearchKey.TransactionDateToKey);
					expenseStatusView.SelectedIndex = expenseStatusView.Items.IndexOf(expenseStatusView.Items.FindByText("Paid"));
					searchCriteria[InsightUtilities.Constants.PurchasingSearchKey.ExpenseStatusViewKey] = expenseStatusView.SelectedIndex.ToString();
				}
				else if(OrderTypeFilterVisible && orderType.SelectedItem.Text == "JE")
				{
					expenseStatusView.SelectedIndex = expenseStatusView.Items.IndexOf(expenseStatusView.Items.FindByText("Paid"));
					searchCriteria[InsightUtilities.Constants.PurchasingSearchKey.ExpenseStatusViewKey] = expenseStatusView.SelectedIndex.ToString();
				}
			}
		}
		#endregion

		#region Internal Methods
		/// <summary>
		/// This method is ONLY invoked by the associated designer to show the control contents at design time.
		/// </summary>
		internal void Design()
		{
			EnsureChildControls();
		}
		#endregion
	}
	#endregion

	#region Class PagerDesigner
	/// <summary>
	/// Designer associated with the PurchasingSearch control.
	/// </summary>
	/// <remarks>
	/// This class cannot be used directly.
	/// </remarks>
	public class PurchasingSearchDesigner : ControlDesigner
	{
		#region Overrides
		/// <summary>
		/// Force the control to create its child controls for display at design time.
		/// </summary>
		/// <returns>HTML representation of the control</returns>
		public override string GetDesignTimeHtml()
		{
			((PurchasingSearch)Component).Design();
			return base.GetDesignTimeHtml();
		}
		#endregion
	}
	#endregion
}
// --- EOF ---